// import { panyuJiweiLogin } from "../../../utils/login.js";
import { jiweiAxios } from "../../../systems/panyu_jiwei/axios.js";
import xlsx from "xlsx";
import { DICT, STATUS, URL } from "../config.js";
import { getBaseParam, checkAnnualExisted } from "../jiweiUtils.js";
import iconv from "iconv-lite";
import cheerio from "cheerio";
import { commonUtil, loginUtil } from "../../../utils/index.js";


const { CRAWL_TWO_DICT, CRAWL_TWO_DICT_INVERT } = commonUtil.getInvertDict(
  DICT,
  "CRAWL_TWO_DICT"
);

const main = async () => {
  const status = await loginUtil.panyuJiweiLogin();
  if (!status) return console.log("登录失败");
  const workbook = xlsx.readFile("./hello.xlsx");
  const sheet = workbook.Sheets[workbook.SheetNames[0]];

  const [, lastCell] = sheet["!ref"].split(":");
  const lastColumn = xlsx.utils.decode_cell(lastCell).c;
  for (let i = 0; i <= lastColumn; i++) {
    const titleCellAddress = `${xlsx.utils.encode_col(i)}1`;
    sheet[titleCellAddress].w =
      CRAWL_TWO_DICT_INVERT[sheet[titleCellAddress].w];
  }
  const personList = xlsx.utils.sheet_to_json(sheet, { defval: "" });

  const { BASE_PARAM, BASE_PARAM1 } = await getBaseParam();
  for (let i = 0; i < personList.length; i++) {
    try {
      let person = personList[i];
      if (person.STATUS) continue;
      const res = await checkAnnualExisted({ person, BASE_PARAM1 });
      if (res.person.STATUS) {
        person.STATUS = res.person.STATUS;
        continue;
      }
      let { ids, date = "" } = await getAnnualId({ ids: res.ids, BASE_PARAM });
      const annual = await getAnnual({ ids });
      // 注意: 这里改变了personList
      date = date ? `最近体检日期：${date}` : "没有体检记录";
      personList[i] = {
        ...personList[i],
        ...annual,
        STATUS: STATUS.FINISH,
        NOTE: date,
      };
    } catch (err) {
      console.error(err);
    }
  }

  personList.forEach((item) => {
    console.log(item);
  });
  const wb = xlsx.utils.book_new();
  const ws = xlsx.utils.json_to_sheet(personList, {
    origin: "A2",
    skipHeader: true,
  });
  const heading = Object.keys(personList[0]).map(
    (item) => CRAWL_TWO_DICT[item]
  );
  xlsx.utils.sheet_add_aoa(ws, [heading]);
  xlsx.utils.book_append_sheet(wb, ws);
  xlsx.writeFile(wb, "hello.xlsx");
};

async function getAnnualId({ ids: originIds, BASE_PARAM }) {
  const ids = { ...originIds };
  const dic = {
    __EVENTTARGET: "btnPersonDataBind",
    __EVENTARGUMENT: "",
    hidPerrecordID: ids.PerrecordID,
    ...BASE_PARAM,
  };

  const res = await jiweiAxios({
    url: URL.ANNUAL_LIST,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    data: commonUtil.jsonToURLString(dic),
    method: "post",
    responseType: "arraybuffer",
  });
  const ANNUAL_LIST = iconv.decode(res.data, "gb2312");
  const $ANNUAL_LIST = cheerio.load(ANNUAL_LIST);

  ids.Chkrecordid = "";
  let date = $ANNUAL_LIST(".TdData tr:not(:first-child)")
    .first()
    .children()
    .first()
    .text();
  if (date.includes("没有查询记录")) {
    date = "";
  } else {
    ids.Chkrecordid =
      $ANNUAL_LIST(".TdData tr:not(:first-child)")
        .first()
        .children()
        .last()
        .children()
        .first()
        .attr("onclick")
        ?.match(/(\d+)/)[1] ?? "";
  }
  return { ids, date };
}

async function getAnnual({ ids }) {
  const annual = {
    ALT: "",
    TBIL: "",
  };
  if (!ids.Chkrecordid) return annual;
  const params = {
    PerrecordID: ids.PerrecordID,
    Name: "",
    Chkrecordid: ids.Chkrecordid,
    record: ids.record,
    ReadOnly: "0",
    Random: "3968",
    From: "AnnualExaminationRegister.aspx",
    Leixing: "1",
    NianJianShenHe_fun: "",
    cmd: "",
    Nianling: "",
  };

  const res = await jiweiAxios({
    url: URL.ANNUAL,
    params,
    responseType: "arraybuffer",
  });
  const HTML = iconv.decode(res.data, "gb2312");
  const $HTML = cheerio.load(HTML);

  return {
    ...annual,
    ALT: $HTML("#ALT").val(),
    TBIL: $HTML("#TBIL").val(),
  };
}

export default main;
